package com.course.chapter3;

/**
 *  懒汉式
 *  优缺点
 *   1.线程安全性  no 指令重排时会有问题
 *   2.性能       还ok
 *   3.懒加载     yes
 * @ClassName: com.course.chapter3.DCLSingleton.java
 * @author: songxulin
 * @date :  2020-06-30 19:01
 * @version V1.0
 */
public class DCLSingleton {
    int a =0;
    int b = 0;
    private static DCLSingleton singleton ;
    /**
     * 私有化构造方法
     */
    private DCLSingleton() {
        //下面可能会发生指令重排
        //后面获取的是时候会引起nullPointerException
        a =10;
        b = 10;
        singleton = new DCLSingleton();
    }

    public  static DCLSingleton getInstance() {
        //第一次检查
        if(singleton == null){
            synchronized (DCLSingleton.class){
                //第二次检查
                if(singleton == null){
                    singleton = new DCLSingleton();
                }
            }
        }
        return singleton;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(()->{
                DCLSingleton instance = DCLSingleton.getInstance();
                System.out.println(instance);
            }).start();
        }

    }
}
